﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Web.Caching;
using System.Data.Linq;

namespace System.Linq
{
    public static class LINQExtension
    {
        public static List<T> LinqCache<T>(this IQueryable<T> q, DataContext dc, string cacheId)
        {


            List<T> objCache = (List<T>)System.Web.HttpRuntime.Cache.Get(cacheId);

            if (objCache == null)
            {
                string connStr = dc.Connection.ConnectionString;
                string sqlCmd = dc.GetCommand(q).CommandText;

                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(sqlCmd, conn))
                    {
                        string NotificationTable = q.ElementType.Name;
                        SqlCacheDependencyAdmin.EnableNotifications(connStr);

                        if (!SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(connStr).Contains(NotificationTable))
                            SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, NotificationTable);

                        SqlCacheDependency sqldep = new SqlCacheDependency(cmd);
                        dc.Refresh(RefreshMode.OverwriteCurrentValues, q);
                        cmd.ExecuteNonQuery();
                        objCache = q.ToList();
                        System.Web.HttpRuntime.Cache.Insert(cacheId, objCache, sqldep);

                    }

                }

            }

            return objCache;

        }
    }
}
